//
//  HomeCircleView.m
//  汽车大灯色温蓝牙
//
//  Created by dfwx on 2020/9/9.
//  Copyright © 2020 zhongdaodianzi. All rights reserved.
//

#import "HomeCircleView.h"

@implementation HomeCircleView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.angle = 0.0;
        self.number = 0;
        self.backgroundColor = [UIColor clearColor];
        
        

    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    
//    [super drawRect:rect];
    
//    [self addLineAction];
    self.number ++;
    if (self.number == 1) {
        self.isChange = YES;
        self.layer.cornerRadius = rect.size.height /2;
        self.layer.masksToBounds = YES;
        CGFloat circleBackWidth = rect.size.height -lin_width -10;
        CGFloat centerWidth = circleBackWidth *0.75;
        
        
        //    if (self.circleBackImageView == nil) {
        self.circleBackImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, rect.size.height, rect.size.height)];
        self.circleBackImageView.center = self.center;
        self.circleBackImageView.image = [UIImage imageNamed:@"fal"];
        self.circleBackImageView.userInteractionEnabled = YES;
        [self addSubview:self.circleBackImageView];
        
        //    }
        self.backImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, rect.size.height*0.85, rect.size.height*0.85)];
        self.backImageView.center = self.center;
        self.backImageView.image = [UIImage imageNamed:@"Pointer01"];
        self.backImageView.contentMode = UIViewContentModeScaleAspectFit;
        self.backImageView.userInteractionEnabled = YES;

        [self addSubview:self.backImageView];
        
        
        //    if (self.circleImageView == nil) {
        self.circleImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, centerWidth, centerWidth)];
        self.circleImageView.center = self.center;
        self.circleImageView.contentMode = UIViewContentModeScaleAspectFit;
        self.circleImageView.image = [UIImage imageNamed:@"share_choice"];
        self.circleImageView.userInteractionEnabled = YES;

        [self addSubview:self.circleImageView];
        //    }
        
        self.centerLabel  = [[UILabel alloc]initWithFrame:self.circleImageView.bounds];
        self.centerLabel.center = self.center;
        self.centerLabel.textColor = [UIColor whiteColor];
        self.centerLabel.textAlignment = NSTextAlignmentCenter;
        self.centerLabel.text = @"LED\nCOLOR";
        self.centerLabel.numberOfLines = 2;
        self.centerLabel.userInteractionEnabled = YES;

        self.centerLabel.font = [UIFont fontWithName:@"FZXiHei I-Z08S" size:22];

        [self addSubview:self.centerLabel];
        
        
        UIRotationGestureRecognizer *gr = [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(panGRAction:)];
        [self addGestureRecognizer:gr];
        
    }

    
}

- (void)panGRAction:(UIRotationGestureRecognizer *)pan {
    
    NSLog(@"旋转了");
    
}

- (void)addLineAction {
    
    
    CGPoint center = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
    
    CGPoint pointStart1 = [self calcCircleCoordinateWithCenter:center andWithAngle:0 andWithRadius:self.frame.size.height/2];
    CGPoint pointEnd1 = [self calcCircleCoordinateWithCenter:center andWithAngle:0 andWithRadius:self.frame.size.height/2-lin_width];
    
    CGPoint pointStart2 = [self calcCircleCoordinateWithCenter:center andWithAngle:45.0 andWithRadius:self.frame.size.height/2];
       CGPoint pointEnd2 = [self calcCircleCoordinateWithCenter:center andWithAngle:45.0 andWithRadius:self.frame.size.height/2-lin_width];
    
    CGPoint pointStart3 = [self calcCircleCoordinateWithCenter:center andWithAngle:90.0 andWithRadius:self.frame.size.height/2];
       CGPoint pointEnd3 = [self calcCircleCoordinateWithCenter:center andWithAngle:90.0 andWithRadius:self.frame.size.height/2-lin_width];
    
    CGPoint pointStart4 = [self calcCircleCoordinateWithCenter:center andWithAngle:135.0 andWithRadius:self.frame.size.height/2];
       CGPoint pointEnd4 = [self calcCircleCoordinateWithCenter:center andWithAngle:135.0 andWithRadius:self.frame.size.height/2-lin_width];
    
    CGPoint pointStart5 = [self calcCircleCoordinateWithCenter:center andWithAngle:180.0 andWithRadius:self.frame.size.height/2];
       CGPoint pointEnd5 = [self calcCircleCoordinateWithCenter:center andWithAngle:180.0 andWithRadius:self.frame.size.height/2-lin_width];
    
    CGPoint pointStart6 = [self calcCircleCoordinateWithCenter:center andWithAngle:225.0 andWithRadius:self.frame.size.height/2];
       CGPoint pointEnd6 = [self calcCircleCoordinateWithCenter:center andWithAngle:225.0 andWithRadius:self.frame.size.height/2-lin_width];
    
    CGPoint pointStart7 = [self calcCircleCoordinateWithCenter:center andWithAngle:315.0 andWithRadius:self.frame.size.height/2];
       CGPoint pointEnd7 = [self calcCircleCoordinateWithCenter:center andWithAngle:315.0 andWithRadius:self.frame.size.height/2-lin_width];
    
    [self drawLineWithStartPoint:pointStart1 withEndPoint:pointEnd1 withAngle:0];
    [self drawLineWithStartPoint:pointStart2 withEndPoint:pointEnd2 withAngle:45.0];
    [self drawLineWithStartPoint:pointStart3 withEndPoint:pointEnd3 withAngle:90.0];
    [self drawLineWithStartPoint:pointStart4 withEndPoint:pointEnd4 withAngle:135.0];
    [self drawLineWithStartPoint:pointStart5 withEndPoint:pointEnd5 withAngle:180.0];
    [self drawLineWithStartPoint:pointStart6 withEndPoint:pointEnd6 withAngle:225.0];
    [self drawLineWithStartPoint:pointStart7 withEndPoint:pointEnd7 withAngle:315.0];
    
    
}

#pragma mark 使用默认context进行绘图
- (void)drawLineWithStartPoint:(CGPoint)startPoint withEndPoint:(CGPoint)endPoint withAngle:(CGFloat)angle
{
    // 对比角度
    CGFloat actualAngle = 0.0;
    if (270 - angle >= 0) {
        actualAngle = 270 -angle ;
    }else {
        actualAngle = 630 - angle ;
    }
    
//    NSLog(@"angle:%f\nactualAngle:%f\nselfAngle:%f",angle,actualAngle,self.angle);
    
    
    //1.获取上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //2.设置当前上下问路径
    //设置起始点
    CGContextMoveToPoint(context, startPoint.x, startPoint.y);
    //增加点
    CGContextAddLineToPoint(context, endPoint.x, endPoint.y);
    CGContextSetLineWidth(context, 2);
    //关闭路径
    CGContextClosePath(context);
    // 线颜色
    if (self.angle == 0) {
        [UIColorFromHex(0xbbbbbb) setStroke];

    }else {
        if (actualAngle < (2*M_PI -self.angle)*360.0 /2.0/M_PI) {
            [UIColorFromHex(0x3ABBDD) setStroke];

        }else {
            [UIColorFromHex(0xbbbbbb) setStroke];


        }
        
    }
    
    //4.绘制路径
    CGContextDrawPath(context, kCGPathFillStroke);
    



    
    
}

#pragma mark - 渐变线
/*
- (void)drawLinearGradient:(CGContextRef)context

                      path:(CGPathRef)path

                startColors:(NSArray *)startColors


{
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    CGFloat locations[] = { 0.0, 1.0 };
    
    NSMutableArray *colors = [NSMutableArray array];
    for (UIColor *color in startColors) {
        CGColorRef colorChange = color.CGColor;
        [colors addObject:(__bridge id)colorChange];
    }
    
//    NSArray *colors = @[(__bridge id) startColor, (__bridge id) endColor];
    
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);
    
    CGRect pathRect = CGPathGetBoundingBox(path);
    
    //具体方向可根据需求修改
    
    CGPoint startPoint = CGPointMake(CGRectGetMidX(pathRect), CGRectGetMinY(pathRect));
    
    CGPoint endPoint = CGPointMake(CGRectGetMidX(pathRect), CGRectGetMaxY(pathRect));
    
    CGContextSaveGState(context);
    
    CGContextAddPath(context, path);
    
    CGContextClip(context);
    
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
    
    CGContextRestoreGState(context);
    
    CGGradientRelease(gradient);
    
    CGColorSpaceRelease(colorSpace);
    
}
*/

- (void)drawLinearGradient:(CGContextRef)context path:(CGPathRef)path colors:(NSArray *)startColors
{
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    CGFloat locations[] = {0.0, 1.0 };
    
    NSMutableArray *colors = [NSMutableArray array];
    for (UIColor *color in startColors) {
        CGColorRef colorChange = color.CGColor;
        [colors addObject:(__bridge id)colorChange];
    }
    
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);
    
    CGRect pathRect = CGPathGetBoundingBox(path);
    
    //具体方向可根据需求修改
    
    CGPoint startPoint = CGPointMake(CGRectGetMinX(pathRect), CGRectGetMidY(pathRect));

    CGPoint endPoint = CGPointMake(CGRectGetMaxX(pathRect), CGRectGetMidY(pathRect));
    
    CGContextSaveGState(context);
    
    CGContextAddPath(context, path);
    
    CGContextClip(context);
    
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
    
    CGContextRestoreGState(context);
    
    CGGradientRelease(gradient);
    
    CGColorSpaceRelease(colorSpace);
    
}



#pragma mark 计算圆圈上点在IOS系统中的坐标
- (CGPoint) calcCircleCoordinateWithCenter:(CGPoint) center  andWithAngle : (CGFloat) angle andWithRadius: (CGFloat) radius{
    CGFloat x2 = radius*cosf(angle*M_PI/180.00);
    CGFloat y2 = radius*sinf(angle*M_PI/180.00);
    return CGPointMake(center.x+x2, center.y-y2);
}
/*
 center中心点坐标
 angle是角度，如果是6个点 应分别传入 60 120 180 240 300 360
 radius半径
 **/

#pragma mark - 三点计算角度


- (CGFloat)getAnglesWithThreePoint:(CGPoint)pointA{
    
    CGPoint pointB = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
    CGPoint pointC = CGPointMake(self.frame.size.width/2, self.frame.size.height);
    


    CGFloat x1 = pointA.x - pointB.x;
    CGFloat y1 = pointA.y - pointB.y;
    CGFloat x2 = pointC.x - pointB.x;
    CGFloat y2 = pointC.y - pointB.y;
    
    CGFloat x = x1 * x2 + y1 * y2;
    CGFloat y = x1 * y2 - x2 * y1;
    
    CGFloat angle = acos(x/sqrt(x*x+y*y));
    if (pointA.x < pointB.x) {
        angle = M_PI *2 -angle;
    }
//    angle = angle *360.0 /2.0/M_PI;
//    NSLog(@"角度%f",angle);
//    if (angle == 2*M_PI) {
//        angle = 0;
//    }
    
    return angle;
}

- (void)timerStart {
    
    [self timerEnd];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.3 repeats:YES block:^(NSTimer * _Nonnull timer) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(HomeCircleViewCircleMoveActionWith:)]) {
            [self.delegate HomeCircleViewCircleMoveActionWith:self.angle];
        }
    }];
    
    
}

- (void)timerEnd {
    [self.timer invalidate];
//    self.timer = nil;
    
}

//- (void)changeTimerStart {
//    [self changeTimerEnd];
//    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.3 repeats:YES block:^(NSTimer * _Nonnull timer) {
//        if (self.delegate && [self.delegate respondsToSelector:@selector(HomeCircleViewCircleMoveActionWith:)]) {
//            [self.delegate HomeCircleViewCircleMoveActionWith:self.angle];
//        }
//    }];
//
//}
//
//- (void)changeTimerEnd {
//    [self.changeTimer invalidate];
////    self.timer = nil;
//
//}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    CGFloat angle = [self getAnglesWithThreePoint:point];
    self.angle = angle;
    self.startPoint = point;
    self.startAngle = angle;
    self.isChange = YES;
    [self timerStart];
    if (self.delegate && [self.delegate respondsToSelector:@selector(HomeCircleViewCircleStartActionWith:)]) {
        [self.delegate HomeCircleViewCircleStartActionWith:self.angle];
    }

}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
//    CGFloat distance = [self distanceBetweenTwoPoint:CGPointMake(self.bounds.size.width/2.0, self.bounds.size.height/2.0) point2:point];
//    if (distance > self.bounds.size.height/2.0*0.85 || distance < self.bounds.size.height/2.0*0.5) {
//        return;
//    }
//    CGFloat startAngle = [self getAnglesWithThreePoint:self.startPoint];
    CGFloat angle = [self getAnglesWithThreePoint:point];
    self.angle = angle;

    
//    CGPoint center = CGPointMake(CGRectGetMidX([touch.view bounds]), CGRectGetMidY([touch.view bounds]));
//    CGPoint currentPoint = [touch locationInView:touch.view];//当前手指的坐标
//    CGPoint previousPoint = [touch previousLocationInView:touch.view];//上一个坐标
//    CGFloat currentAngle = [self getAnglesWithThreePoint:currentPoint];
//    CGFloat previousAngle = [self getAnglesWithThreePoint:previousPoint];
//
//    self.currentPoint = currentAngle;
//    self.lastPoint = previousAngle;
    
    
    
//    if (currentAngle > previousAngle) {
//        // 逆时针
//        if (angle > self.startAngle && angle < 2*M_PI) {
//            self.angle = angle;
//            self.locationPoint = point;
//        }
//        NSLog(@"逆时针赋值:%f",self.angle);
//
//    }
//
//    if (currentAngle < previousAngle) {
//        // 顺时针
//        if (angle < self.startAngle && angle > 0) {
//            self.angle = angle;
//
//        }else {
//            self.startAngle = 0;
//        }
//        NSLog(@"顺时针赋值:%f",self.angle);
//
//    }
    
    
    


        




}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (self.delegate && [self.delegate respondsToSelector:@selector(HomeCircleViewCircleEndLearnActionWith:)]) {
        [self.delegate HomeCircleViewCircleEndLearnActionWith:self.angle];
    }
    
    UITouch *touch = [touches anyObject];

    CGPoint point = [touch locationInView:self];
    CGFloat angle = [self getAnglesWithThreePoint:point];
    [self timerEnd];
    
    self.angle = angle;
    if (self.delegate && [self.delegate respondsToSelector:@selector(HomeCircleViewCircleClickedActionWith:)]) {
        [self.delegate HomeCircleViewCircleClickedActionWith:self.angle /(2*M_PI)];
    }

}

- (void)delegateTransValue {
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(HomeCircleViewCircleClickedActionWith:)]) {
        [self.delegate HomeCircleViewCircleClickedActionWith:self.angle /(2*M_PI)];
    }
}

- (void)setAngle:(CGFloat)angle {
    
    _angle = angle;
    self.circleImageView.transform = CGAffineTransformMakeRotation(-angle);
    
    NSInteger a = (2*M_PI-angle)/(M_PI/4.0);
    NSLog(@"%ld\n%f\n%f",a,(2*M_PI-angle),(M_PI/4.0));
//    self.backImageView.image = [UIImage imageNamed:@"Pointer%02ld",a];
//    if (2 *M_PI == angle) {
//
//    }
//    [self setNeedsDisplay];
    
//    NSString *string = [NSString stringWithFormat:<#(nonnull NSString *), ...#>]
    
    self.backImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"Pointer%02ld",a+1]];

}

- (CGFloat)getAnglesWithThreePoint:(CGPoint)pointA pointB:(CGPoint)pointB pointC:(CGPoint)pointC {
    
    CGFloat x1 = pointA.x - pointB.x;
    CGFloat y1 = pointA.y - pointB.y;
    CGFloat x2 = pointC.x - pointB.x;
    CGFloat y2 = pointC.y - pointB.y;
    
    CGFloat x = x1 * x2 + y1 * y2;
    CGFloat y = x1 * y2 - x2 * y1;
    
    CGFloat angle = acos(x/sqrt(x*x+y*y));
    
    if (pointC.x < pointB.x) {
        angle = M_PI*2 - angle;
    }
    
    return angle;
}

-(float)distanceBetweenTwoPoint:(CGPoint)point1 point2:(CGPoint)point2
{
    
    return sqrtf(powf(point1.x - point2.x, 2) + powf(point1.y - point2.y, 2));
}


@end
